package com.example.firstfive;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.os.Handler;

public class MapTask implements Runnable {
   private static final String TAG="MyTask";
    private Handler handler;
    private String logDate = "";//用于保存从SP里获得数据
    private final String DATE_SP_KEY = "lastRateDateStr";//用于记录保存在SP中的数据KEY，


   public void setHandler(Handler handler){
        this.handler = handler;
   }
//    @Override
//    public void run() {
//        Log.i("List","run...");
//        List<String> retList = new ArrayList<String>();
//        Message msg = handler.obtainMessage();
//        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
//        Log.i("run","curDateStr:" + curDateStr + " logDate:" + logDate);
//        if(curDateStr.equals(logDate)){
//            //如果相等，则不从网络中获取数据
//            Log.i("run","日期相等，从数据库中获取数据");
//            DBManager dbManager = new DBManager(RateListActivity.this);
//            for(RateItem rateItem : dbManager.listAll()){
//                retList.add(rateItem.getCurName() + "=>" + rateItem.getCurRate());
//            }
//        }else{
//            Log.i("run","日期相等，从网络中获取在线数据");
//            //获取网络数据
//            try {
//                List<RateItem> rateList = new ArrayList<RateItem>();
//                URL url = new URL("http://www.usd-cny.com/bankofchina.htm");
//                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//                InputStream in = httpConn.getInputStream();
//                String retStr = IOUtils.toString(in,"gb2312");
//
//                //Log.i("WWW","retStr:" + retStr);
//                //需要对获得的html字串进行解析，提取相应的汇率数据...
//
//                Document doc = Jsoup.parse(retStr);
//                Elements tables  = doc.getElementsByTag("table");
//
//                Element retTable = tables.get(5);
//                Elements tds = retTable.getElementsByTag("td");
//                int tdSize = tds.size();
//                for(int i=0;i<tdSize;i+=8){
//                    Element td1 = tds.get(i);
//                    Element td2 = tds.get(i+5);
//                    //Log.i("www","td:" + td1.text() + "->" + td2.text());
//                    float val = Float.parseFloat(td2.text());
//                    val = 100/val;
//                    retList.add(td1.text() + "->" + val);
//
//                    RateItem rateItem = new RateItem(td1.text(),td2.text());
//                    rateList.add(rateItem);
//                }
//                DBManager dbManager = new DBManager(Ratethis);
//                dbManager.deleteAll();
//                Log.i("db","删除所有记录");
//                dbManager.addAll(rateList);
//                Log.i("db","添加新记录集");
//
//            } catch (MalformedURLException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//            //更新记录日期
//            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
//            SharedPreferences.Editor edit = sp.edit();
//            edit.putString(DATE_SP_KEY, curDateStr);
//            edit.commit();
//            Log.i("run","更新日期结束：" + curDateStr);
//        }
//
//        msg.obj = retList;
//        msg.what = msgWhat;
//        handler.sendMessage(msg);
//    }
   @Override
   public void run(){
       //获取网络数据
      Log.i(TAG, "run: run()......");
     //do....延时
      try {
           Thread.sleep(3000);
       } catch (InterruptedException e) {
          e.printStackTrace();
       }
      List<HashMap<String,String>> retlist= new ArrayList<HashMap<String,String>>();
       try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();//https标示加密传输
           String title = doc.title();
           Log.i(TAG,"run: title="+doc.title());
           Elements table = doc.getElementsByTag("table");
             // table.get(1);从第2个table开始
            Elements trs = table.get(1).getElementsByTag("tr");
             //    读取标识符tr中的字符
           for(Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
                  //按行标识符读取
                Log.i(TAG,"run:td.size="+tds.size());
                if(tds.size()>0){
                    //提取数据
                   String td1 = tds.get(0).text();
                 String td2 = tds.get(5).text();
                  Log.i(TAG,"run:"+td1+"==>"+td2);
                  // retlist.add(td1+"==>"+td2);
                    HashMap<String,String> map =new HashMap<String,String>();
                    map.put("cname",td1);
                    map.put("cval",td2);
                    retlist.add(map);
                }
           }
        } catch (IOException e) {
            e.printStackTrace();
       }
         //返回消息给主线程
        //获取Msg对象，用于返回主线程
       Message msg = handler.obtainMessage(7,retlist);
        handler.sendMessage(msg);
        Log.i(TAG, "run: sendMessage ok");
  }
    }




